import datetime
from datetime import timedelta
import json
import os

class TimeCalculatorCLI:
    def __init__(self):
        self.history_file = "time_calculator_history.json"
        self.history = self.load_history()
    
    def load_history(self):
        """加载历史记录"""
        if os.path.exists(self.history_file):
            try:
                with open(self.history_file, "r") as f:
                    return json.load(f)
            except:
                return []
        return []
    
    def save_history(self, start_time, end_time, result):
        """保存历史记录"""
        history_entry = {
            "timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "start_time": start_time,
            "end_time": end_time,
            "result": result
        }
        
        self.history.append(history_entry)
        
        # 只保留最近的10条记录
        if len(self.history) > 10:
            self.history = self.history[-10:]
        
        try:
            with open(self.history_file, "w") as f:
                json.dump(self.history, f, indent=2)
        except Exception as e:
            print(f"⚠️  无法保存历史记录: {str(e)}")
    
    def display_history(self):
        """显示历史记录"""
        if not self.history:
            print("📜 暂无历史记录")
            return
        
        print("📜 历史计算记录:")
        print("-" * 80)
        for i, entry in enumerate(reversed(self.history), 1):
            print(f"{i}. {entry['timestamp']}")
            print(f"   {entry['start_time']} -> {entry['end_time']} = {entry['result']}")
            print()
    
    def clear_history(self):
        """清除历史记录"""
        confirm = input("❓ 确定要清除所有历史记录吗？(y/n): ").lower()
        if confirm == 'y':
            self.history = []
            try:
                if os.path.exists(self.history_file):
                    os.remove(self.history_file)
                print("✅ 历史记录已清除")
            except Exception as e:
                print(f"⚠️  无法清除历史记录: {str(e)}")
        else:
            print("🚫 已取消清除操作")
    
    def load_selected_history(self):
        """加载选中的历史记录"""
        self.display_history()
        if not self.history:
            return None, None
        
        try:
            index = int(input("请输入要加载的记录编号: "))
            if 1 <= index <= len(self.history):
                entry = self.history[-index]
                return entry['start_time'], entry['end_time']
            else:
                print("❌ 无效的记录编号")
        except ValueError:
            print("❌ 请输入有效的数字")
        return None, None
    
    def get_time_input(self, prompt, default=None):
        """获取时间输入"""
        while True:
            if default:
                time_str = input(f"{prompt} (默认: {default}): ") or default
            else:
                time_str = input(f"{prompt}: ")
            
            if time_str.lower() == 'q':
                return None
            
            # 验证时间格式
            if len(time_str.split(':')) == 3:
                try:
                    h, m, s = map(int, time_str.split(':'))
                    if 0 <= h < 24 and 0 <= m < 60 and 0 <= s < 60:
                        return time_str
                    else:
                        print("❌ 时间值超出范围 (小时: 0-23, 分钟: 0-59, 秒: 0-59)")
                except ValueError:
                    print("❌ 请输入有效的数字")
            else:
                print("❌ 时间格式错误，请使用 HH:MM:SS 格式")
    
    def calculate_time_difference(self, start_time_str, end_time_str, cross_day=False):
        """计算时间间隔"""
        try:
            # 解析时间
            start_h, start_m, start_s = map(int, start_time_str.split(':'))
            end_h, end_m, end_s = map(int, end_time_str.split(':'))
            
            # 创建时间对象
            start_time = datetime.datetime(2023, 1, 1, start_h, start_m, start_s)
            end_time = datetime.datetime(2023, 1, 1, end_h, end_m, end_s)
            
            # 检查是否跨天
            if cross_day and end_time < start_time:
                end_time += timedelta(days=1)
            
            # 计算时间差
            time_diff = end_time - start_time
            
            # 提取天、小时、分钟、秒
            days = time_diff.days
            seconds = time_diff.seconds
            hours = seconds // 3600
            minutes = (seconds % 3600) // 60
            seconds = seconds % 60
            
            # 格式化结果
            result = f"{days}天{hours}小时{minutes}分钟{seconds}秒"
            total_seconds = time_diff.total_seconds()
            
            # 显示结果
            print("\n" + "=" * 50)
            print("⏰ 计算结果:")
            print(f"起始时间: {start_time_str}")
            print(f"结束时间: {end_time_str}")
            print(f"跨天计算: {'是' if cross_day else '否'}")
            print("-" * 30)
            print(f"时间间隔: {result}")
            print(f"总秒数: {total_seconds}")
            print("=" * 50 + "\n")
            
            # 保存历史记录
            self.save_history(start_time_str, end_time_str, result)
            
            return True
            
        except ValueError as e:
            print(f"❌ 输入错误: {str(e)}")
        except Exception as e:
            print(f"❌ 计算错误: {str(e)}")
        return False
    
    def display_menu(self):
        """显示菜单"""
        print("=" * 50)
        print("⌚ 时间间隔计算器 (命令行版)")
        print("=" * 50)
        print("1. 计算时间间隔")
        print("2. 查看历史记录")
        print("3. 清除历史记录")
        print("4. 从历史记录加载")
        print("5. 退出")
        print("=" * 50)
    
    def run(self):
        """运行计算器"""
        print("欢迎使用时间间隔计算器！")
        print("输入 'q' 可以随时返回上一级\n")
        
        while True:
            self.display_menu()
            choice = input("请选择功能 (1-5): ")
            
            if choice == '1':
                # 计算时间间隔
                print("\n📅 计算时间间隔")
                print("-" * 30)
                
                start_time = self.get_time_input("请输入起始时间 (HH:MM:SS)", "00:00:00")
                if start_time is None:
                    continue
                
                end_time = self.get_time_input("请输入结束时间 (HH:MM:SS)", "23:59:59")
                if end_time is None:
                    continue
                
                cross_day = input("是否跨天计算? (y/n, 默认: n): ").lower() == 'y'
                
                self.calculate_time_difference(start_time, end_time, cross_day)
                
            elif choice == '2':
                # 查看历史记录
                print("\n📜 历史记录")
                print("-" * 30)
                self.display_history()
                
            elif choice == '3':
                # 清除历史记录
                print("\n🗑️  清除历史记录")
                print("-" * 30)
                self.clear_history()
                
            elif choice == '4':
                # 从历史记录加载
                print("\n🔄 从历史记录加载")
                print("-" * 30)
                start_time, end_time = self.load_selected_history()
                
                if start_time and end_time:
                    print(f"\n已加载: {start_time} -> {end_time}")
                    calculate = input("是否立即计算? (y/n): ").lower()
                    if calculate == 'y':
                        cross_day = input("是否跨天计算? (y/n, 默认: n): ").lower() == 'y'
                        self.calculate_time_difference(start_time, end_time, cross_day)
                
            elif choice == '5':
                # 退出
                print("\n👋 感谢使用，再见！")
                break
                
            else:
                print("❌ 无效的选择，请输入 1-5 之间的数字")
            
            input("\n按回车键继续...")
            print()

if __name__ == "__main__":
    calculator = TimeCalculatorCLI()
    calculator.run()
